package jwdt.xadmin.system.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jwdt.common.bean.Tree;
import jwdt.common.dao.BaseDao;
import jwdt.xadmin.system.bean.TDep;
import jwdt.xadmin.system.service.DeptManageService;

import com.ezerg.db.Jdb;
import com.ezerg.db.ext.PageUtil;
import com.ezerg.fastjson.JSON;
import com.ezerg.util.StringUtil;

public class DeptManageServiceImpl implements DeptManageService {
	
	private BaseDao<TDep> baseDao;
	
	public void setBaseDao(BaseDao<TDep> baseDao) {
		this.baseDao = baseDao;
	}
	
	@Override
	public String doListDept(PageUtil pu) throws Exception{
		String sql = " order by px";
		pu.doList(TDep.class,sql);
		//创造json数据对象
		@SuppressWarnings({ "unused", "rawtypes" })
		Map jsonObj = new HashMap();
		StringBuffer s = new StringBuffer();
		s.append("{\"rows\":").append(JSON.toJSON(pu.getResult()).toString().replaceAll("fid", "_parentId"));
		s.append(",\"total\":").append(pu.getTotal()).append("}");
		return s.toString();
	}
	
	@Override
	public String doAddact(TDep tDept) throws Exception {
		return baseDao.doAddObj(tDept);
	}

	@Override
	public String doEditact(TDep tDept, int id) throws Exception {
		return baseDao.doUpdateObj(TDep.class, id, tDept);
	}
	
	@Override
	public String doDelact(int id) throws Exception {
		@SuppressWarnings("unchecked")
		List<TDep> list = Jdb.get().query(TDep.class, "fid="+id);
		if(list.size()>0){
			for (TDep tDep : list) {
				doDelact(StringUtil.parseInt(tDep.getId()));
			}
		}
		return baseDao.doDelObj(TDep.class, id);
	}

	@Override
	public TDep doLoad(int id) throws Exception {
		return baseDao.doLoadObj(TDep.class, id);
	}
	@Override
	public String doUpdateState(int id, String result) throws Exception {
		return baseDao.doIntUpdateState(TDep.class, "id="+id, result);
	}

	@Override
	@SuppressWarnings("unchecked")
	public String doListDepForTree() throws Exception {
		List<Tree> treeList = new ArrayList<Tree>();
		List<TDep> list = Jdb.get().query(TDep.class,"fid=0 order by id");
		Tree tree = new Tree();
		tree.setId("0");
		tree.setText("组织机构");
		tree.setIconCls("icon-role");
		tree.setChildren(treeList(list));
		treeList.add(tree);
		return JSON.toJSONString(treeList);
	}
	
	@SuppressWarnings("unchecked")
	public List<Tree> treeList(List<TDep> list){
		List<Tree> treeList = new ArrayList<Tree>();
		for (TDep dep : list) {
			Tree tree = new Tree();
			tree.setId(dep.getId()+"");
			tree.setText(dep.getName());
			if(!dep.getChildren().isEmpty()){
				tree.setChildren(treeList(dep.getChildren()));
			}
			treeList.add(tree);
		}
		return treeList;
	}
}
